'use strict';

(function(angular) {
    // 由于默认angular提供的异步请求对象不支持自定义回调函数名
    // angular随机分配的回调函数名称不被豆瓣支持
    let http = angular.module('moviecat.services.http', []);
    http.service('HttpService', ['$window', '$document', function($window, $document) {
        // console.log($document);
        // url : http://api.douban.com/vsdfsdf -> <script> -> html就可自动执行
        this.jsonp = function(url, data, callback) {
            let cbFuncName = `angular_${Date.now().toString()}`
            url = (url.indexOf('?') == -1) ? `${url}?` : '';
            for (let key in data) {
                url += `${key}=${data[key]}&`;
            }
            url += 'callback=' + cbFuncName;

            let scriptElement = $document[0].createElement('script');
            scriptElement.src = url;
            $window[cbFuncName] = function(data) {
                callback(data);
                $document[0].body.removeChild(scriptElement);
            };
            $document[0].body.appendChild(scriptElement);
        };
    }]);
})(angular);